package com.firesrc.util;

import java.io.StringWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;

import jodd.db.DbQuery;
import jodd.util.PrettyStringBuilder;

import org.h2.tools.Csv;

import com.firesrc.db.DBManager;

public class DataSyncUtil {

  public static synchronized String getSyncUnFetchKeywordCsvString() {
    StringWriter writer = new StringWriter();
    try {
      Connection conn = DBManager.getPublicConnectionPool().getConnection();
      Statement stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      //查找还没有找出关键字,并且flag状态是f的记录 flag=c(complete)表示已经上传完成  flag=p(pending)表示还在本地,没有上次到服务器
      // flag=f(fetch) 表示当前关键字已经被客户端索取查找,不需要本地再搜索
      String sql = "select top 2 * from keyword where state='0' and flag!=" + SystemConfigConstant.KEYWORD_STATE_FETCH;
      ResultSet rs = stat.executeQuery(sql);
      Set<String> keywordSet = new HashSet<String>();
      Csv csv = SqlTsvTool.getCurrentCsv();
      while (rs.next()) {
        keywordSet.add("'" + rs.getString("NAME") + "'");
      }
      String keywordNames = PrettyStringBuilder.str(keywordSet);
      rs.beforeFirst();
      csv.write(writer, rs);
      String string = "update keyword set flag=" + SystemConfigConstant.KEYWORD_STATE_FETCH + " where name in" + keywordNames;
      System.out.println("sql:" + string);
      new DbQuery(conn, string).executeUpdateAndClose();
      DBManager.getPublicConnectionPool().closeConnection(conn);
    } catch (Exception e) {
      e.printStackTrace();
    }

    String string = writer.toString();
    return string;

  }
}
